<template>
  <picker-view
    :indicator-style="indicatorStyle"
    :value="inDate"
    @change="bindChange"
    class="picker-view"
  >
    <picker-view-column v-show="optional.includes('Y')">
      <view class="picker-item" v-for="(item, index) in years" :key="index"
        >{{ item }}年</view
      >
    </picker-view-column>
    <picker-view-column v-show="optional.includes('M')">
      <view class="picker-item" v-for="(item, index) in months" :key="index"
        >{{ item }}月</view
      >
    </picker-view-column>
    <picker-view-column v-show="optional.includes('D')">
      <view class="picker-item" v-for="(item, index) in days" :key="index"
        >{{ item }}日</view
      >
    </picker-view-column>
  </picker-view>
</template>

<script setup>
import { ref } from "vue";
const props = defineProps({
  initDate: {
    type: Array,
    default: () => {
      return [];
    },
  },
  optional: {
    type: String,
    default: "YMD",
  },
});
const inDate = ref([]); //牧人显示时间下标数组
const years = ref([]); //年月日滚动数组
const months = ref([]);
const days = ref([]);
const year = ref(new Date().getFullYear()); //初始化年月日
const month = ref(new Date().getMonth() + 1);
const day = ref(new Date().getDate());
const indicatorStyle = `height: 100rpx;`;
const emit = defineEmits(["changeDate"]); //父组件事件

// 初始化
const init = () => {
  years.value = [];
  months.value = [];
  days.value = [];
  for (let i = 1990; i <= year.value; i++) {
    years.value.push(i);
  }
  for (let i = 1; i <= 12; i++) {
    months.value.push(i);
  }
  for (let i = 1; i <= 31; i++) {
    days.value.push(i);
  }
  setTimeout(() => {
    if (props.initDate.length == 0) {
      // console.log("无初始值");
      const yearIndex = years.value.indexOf(year.value);
      inDate.value = [yearIndex, month.value - 1, day.value - 1];
      console.log("无初始值", inDate.value);
    } else {
      // 在years.value获取props.initDate[0]下标
      const yearIndex = years.value.indexOf(props.initDate[0]);
      inDate.value = [yearIndex, props.initDate[1] - 1, props.initDate[2] - 1];
      console.log("有初始值", inDate.value);
    }
  }, 100);
};
init();

// 滑动改变后传给父级元素
const bindChange = (e) => {
  const val = e.detail.value;
  let dateArray = [
    years.value[val[0]],
    months.value[val[1]],
    days.value[val[2]],
  ];
  emit("changeDate", dateArray);
};
</script>

<style scoped lang="less">
.picker-view {
  height: 560rpx;
}
.picker-item {
  line-height: 100rpx;
  text-align: center;
  font-size: 24rpx;
}
</style>
